package cn.javaSong.controller;

import cn.javaSong.common.ResponseHelper;
import cn.javaSong.common.ResponseModel;
import cn.javaSong.entity.Img;
import cn.javaSong.mapper.ImgMapper;
import cn.javaSong.service.IImgService;
import cn.javaSong.utils.StringUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dakai
 * @since 2024-10-30
 */
@RestController
@RequestMapping("/img")
public class ImgController {
    @Resource
    private IImgService iImgService;

    @Resource
    private ImgMapper imgMapper;

    @PostMapping("/add")
    public ResponseModel<Img> getPcGirlWallpaper() {
        return iImgService.getPcGirlWallpaper();
    }
    //删除图片文件并删除数据库信息
    @PostMapping("/deleteImg")
    @ResponseBody
    public ResponseModel delFile(String path) {
        String resultInfo = null;
        int lastIndexOf = path.lastIndexOf("/");
        String img_path = path.substring(lastIndexOf + 1, path.length());
        img_path = "D:/asong/" + img_path;
        File file = new File(img_path);
        if (file.exists()) {//文件是否存在
            if (file.delete()) {//存在就删了，返回-【D:/asong/20241026025530000000350.png】删除成功";
                iImgService.delImg(path);
                resultInfo =  "【" + img_path + "】删除成功";
            } else {
                resultInfo =  "【" + img_path + "】不存在，删除失败";
            }
        } else {
            resultInfo = "文件不存在！";
        }
        return ResponseHelper.successMessage(resultInfo);
    }

    @PostMapping("/deleteById")
    public ResponseModel deleteByIname(@RequestBody List<String> inames) {
        int count = imgMapper.deleteById(inames);
        if (count > 0) {
            return ResponseHelper.successMessage("删除成功");
        } else{
            return ResponseHelper.error("数据不存在，删除失败");
        }
    }

    /**
     * 批量新增
     * @param imgs
     * @return
     */
    @PostMapping("/insertBatch")
    public ResponseModel insertBatch(@RequestBody List<Img> imgs) {
        List<Img> list = new ArrayList<>();
        for (Img img: imgs) {
            list.add(img.setId(StringUtil.createUUID()));
        }
        imgMapper.insertBatch(list);
        return ResponseHelper.successMessage("添加成功");
    }
}
